package com.future.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.future.domain.AnswerSheet;
import com.future.domain.AverageScore;
import com.future.mapper.AnswerSheetMapper;
import com.future.mapper.AverageScoreMapper;

import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.time.LocalDate;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SchedulingTask {
        @Resource
        private AnswerSheetMapper answerSheetMapper; // 注入MyBatis Mapper
        @Resource
        private StringRedisTemplate stringRedisTemplate;
        @Resource
        private AverageScoreMapper averageScoreMapper;

    /**
         * 每天凌晨2点执行任务
         * cron表达式格式：秒 分 时 日 月 周 年(可选)
         */
        @Scheduled(cron = "0 0 2 * * ?")
        public void executeMyBatisTask() {
            double averageScore = 0d;
            try {
                LambdaQueryWrapper<AnswerSheet> queryWrapper = new LambdaQueryWrapper<>();
                // 指定查询 score 字段
                queryWrapper.select(AnswerSheet::getTotalScore);
                // 获取 score 字段的集合
                List<Object> scoreList = answerSheetMapper.selectObjs(queryWrapper);
                // 将 Object 类型的集合转换为 Integer 类型的集合
                List<Integer> scores = scoreList.stream()
                        .map(obj -> (Integer) obj)
                        .collect(Collectors.toList());
                if (!scores.isEmpty()) {
                    averageScore = scores.stream()
                            .mapToInt(Integer::intValue)
                            .average()
                            .orElse(0.0);
                }
            } catch (Exception e) {
                log.info("获取平均分数失败",e);
                throw new RuntimeException(e);
            }
            LocalDate now = LocalDate.now();
            averageScoreMapper.insert(new AverageScore(now,(int) averageScore));
            stringRedisTemplate.opsForValue().set(now.toString(),String.valueOf(averageScore));
            log.info("平均分数为:{}",averageScore);
        }


}
